package net.lcheng.sellerCenter.controller;

import com.alibaba.fastjson.JSON;
import com.sun.tracing.dtrace.ModuleAttributes;
import net.lcheng.commons.utils.PageList;
import net.lcheng.model.*;
import net.lcheng.sellerCenter.vo.ProductUnityFormatModel;
import net.lcheng.service.CategoryService;
import net.lcheng.service.ProductService;
import net.lcheng.service.UserService;
import net.lcheng.service.WxShopService;
import net.lcheng.vo.ProductConditionsSelectModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LV on 2016/6/29.
 */
@Controller
public class ProductPublishController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private WxShopService wxShopService;
    @Autowired
    private ProductService productService;

    private static final int PAGE_SIZE=2;

    /**
     * 异步获取分类列表
     * @param parentCategoryId
     * @return
     */
    @RequestMapping(value = "/product/getClassifyList/{parentCategoryId}",method = RequestMethod.GET)
    @ResponseBody
    public String getClassifyList(@PathVariable("parentCategoryId") String parentCategoryId){
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (parentCategoryId.equals("no"))
                parentCategoryId = "";
            List<PCategory> list = categoryService.findCategoryListByParentCategoryId(parentCategoryId);
            return JSON.toJSONString(list);
        }
        return "";
    }

    /**
     * 选择商品发布分类
     * @return
     */
    @RequestMapping(value = "/product/productClassify",method = RequestMethod.GET)
    public String productClassify(){
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            return "product_manage/product_publish_category_select";
        }
        return "redirect:/login";
    }


    /**
     * 保存商品分类
     * @param model
     * @param categoryId 选择的分类ID
     * @return
     */
    @RequestMapping(value = "/product/savingProductClassify",method = RequestMethod.GET)
    public String savingProductClassify(Model model, @RequestParam("cid") String categoryId){
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            ProductUnityFormatModel formatModel=new ProductUnityFormatModel();
            formatModel.setCategoryId(categoryId);

            //获取分类父分类名,递归查询,然后倒序转换
            List<String> categoryNames=categoryService.getParentCategoryName(categoryId);
            Collections.reverse(categoryNames);

            formatModel.setCategoryName(categoryNames);

            model.addAttribute("unityFormat",formatModel);

            return "product_manage/product_publish_product_infor";
        }
        return "redirect:/login";
    }

    /**
     * 保存商品信息,发布商品
     * @return
     */
    @RequestMapping(value = "/product/savingProductInformation",method = RequestMethod.POST)
    public String savingProductInformation(Model model,@Valid @ModelAttribute("unityFormatModel") ProductUnityFormatModel unityFormatModel, BindingResult result){
        if(result.hasErrors()){
            //获取分类父分类名,递归查询,然后倒序转换
            List<String> categoryNames=categoryService.getParentCategoryName(unityFormatModel.getCategoryId());
            Collections.reverse(categoryNames);
            unityFormatModel.setCategoryName(categoryNames);

            model.addAttribute("unityFormat",unityFormatModel);
            return "product_manage/product_publish_product_infor";
        }
        //获取当前用户
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()){
            //将上传的图片的url拼接起来，用“|”分割
            String imgs="";
            if (unityFormatModel.getProductImgs()!=null&&unityFormatModel.getProductImgs().length>0){
                String[] imgTmp=unityFormatModel.getProductImgs();
                for (int $i=0;$i<imgTmp.length;$i++){
                    if (imgTmp[$i].equals("")&&imgTmp[$i]!=null) continue;
                    imgs+=(imgTmp[$i]+"|");
                }
                imgs=imgs.substring(0,imgs.lastIndexOf("|"));
            }
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if (user!=null){
                //获取商店信息
                WxShop shop=wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null){
                   //取得商店的shopId
                    int shopId=shop.getShopId();
                    //保存发布的商品信息
                    PProduct pProduct=new PProduct();
                    pProduct.setProductId(UUID.randomUUID().toString());
                    pProduct.setpCategoryCategoryId(unityFormatModel.getCategoryId());//产品分类Id
                    pProduct.setWxShopShopId(shopId);//店铺Id
                    pProduct.setWxShopCategoryId(unityFormatModel.getShopCategoryId());//店铺分类Id
                    pProduct.setProductCode(unityFormatModel.getProductCode());
                    pProduct.setProductName(unityFormatModel.getProductName());
                    pProduct.setProductMainImage(unityFormatModel.getProductImgs()[0]);//主图片
                    pProduct.setProductImages(imgs);//上传的所有图片的URL地址
                    pProduct.setAddrProvinceName(unityFormatModel.getAddrProvinceName());//发货省份名
                    pProduct.setAddrProvinceCode(unityFormatModel.getAddrProvinceCode());//发货省份地址代码
                    pProduct.setAddrCityName(unityFormatModel.getAddrCityName());//发货城市名
                    pProduct.setAddrCityCode(unityFormatModel.getAddrCityCode());//发货城市代码
                    pProduct.setInventoryNum(Integer.parseInt(unityFormatModel.getInventoryNum()));//库存数
                    pProduct.setMarketPrice(new BigDecimal(unityFormatModel.getMarketPrice()));//市场价
                    pProduct.setSalePrice(new BigDecimal(unityFormatModel.getSalePrice()));//零售价
                    pProduct.setIsShopRecommend(1);//默认情况为店长推荐
                    pProduct.setProductDescription(unityFormatModel.getProductDescription());//商品描述
                    pProduct.setStatus(1);//发布商品时状态为上架状态
                    pProduct.setFreight(new BigDecimal(unityFormatModel.getFreight()));//运费
                    pProduct.setCreateOn(new Date());//创建时间
                    //保存发布信息
                    int status=productService.publishProduct(pProduct);
                    if (status>0)
                        return "product_manage/product_publish_success";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 获取所有商品列表
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(value = "/product/productListAll",method = RequestMethod.GET)
    public String productListAll(Model model,@RequestParam(value = "page",defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum = currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user = userService.getUserByPhone(userPhoneNum);
            if (user != null) {
                //获取商店信息
                WxShop shop = wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null) {
                    //取得商店的shopId
                    int shopId = shop.getShopId();

                    PageList<PProduct> pageList = productService.getProductListAll(shopId, PAGE_SIZE, page);

                    model.addAttribute("productList", pageList.list);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数
                    return "/product_manage/product_list_all";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }



    /**
     * 商品列表
     * @param status 状态（0已下架1销售中2禁售中）
     * @return
     */
   @RequestMapping(value = "/product/productList",method = RequestMethod.GET)
    public String productList(Model model,@RequestParam("status") int status
           ,@RequestParam(value = "page",defaultValue = "1") int page){
       Subject currentUser= SecurityUtils.getSubject();
       if(currentUser.isAuthenticated()) {
           String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
           //获取用户信息
           User user=userService.getUserByPhone(userPhoneNum);
           if (user!=null) {
               //获取商店信息
               WxShop shop = wxShopService.getShopInforByUserId(user.getUserId());

               if (shop!=null){

                       PageList<PProduct> pageList = productService.getProductListByStatus(shop.getShopId(), status,PAGE_SIZE,page);
                       model.addAttribute("productList", pageList.list);//产品列表
                       model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                       model.addAttribute("totalPage", pageList.totalPage);//总页数
                       model.addAttribute("totalCount", pageList.totalCount);//总记录数

                       //跳转到下架产品列表
                       if (status == 0)
                           return "product_manage/product_list_undercarriage";

                       //跳转上架产品列表
                       if (status == 1)
                           return "product_manage/product_list_grounding";
               }
           }
           return "redirect:/error";
       }
       return "redirect:/login";
   }


    /**
     * 改变销售状态
     * @param status 状态（0已下架1销售中2禁售中）
     */
    @RequestMapping(value = "/product/updateProductStatus",method = RequestMethod.GET)
    public String updateProductStatus(@RequestParam("pId") String productId,@RequestParam("status") int status){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (productId!=null){
                int ps=productService.updateProductStatus(productId,status);
                if (ps>0)
                    return "redirect:/product/productList/?status="+status;
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 改变店铺推荐状态
     * @return
     */
    @RequestMapping(value = "/product/updateProductRecommendStatus",method = RequestMethod.GET)
    public String  updateProductRecommendStatus(@RequestParam("pId") String productId,@RequestParam("status") int status){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (productId!=null){
                int ps=productService.updateProductRecommendStatus(productId,status);
                //更新成功
                if(ps>0){
                    //查看该产品的上架状态
                    PProduct pProduct=productService.getProductByPrimaryKey(productId);
                    if (pProduct!=null){
                        int groundingStatus=pProduct.getStatus();
                        return "redirect:/product/productList?status="+groundingStatus;
                    }
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 编辑商品
     * @param model
     * @param productId
     * @return
     */
    @RequestMapping(value = "/product/editProduct",method = RequestMethod.GET)
    public String editProduct(Model model,@RequestParam("pId") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            //查询商品信息
            if (productId!=null){
                PProduct product=productService.getProductByPrimaryKey(productId);
                if (product!=null){
                    model.addAttribute("product",product);

                    String img=product.getProductImages();
                    //将图片地址分割
                    String[] imgs=img.split("\\|");
                    model.addAttribute("imgs",imgs);

                    //获取分类父分类名,递归查询,然后倒序转换
                    List<String> categoryNames=categoryService.getParentCategoryName(product.getpCategoryCategoryId());
                    Collections.reverse(categoryNames);

                    model.addAttribute("categoryNames",categoryNames);

                    return "/product_manage/product_publish_product_edit";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存编辑的商品
     * @param unityFormatModel
     * @return
     */
    @RequestMapping(value = "/product/savingEditProduct",method = RequestMethod.POST)
    public String savingEditProduct(Model model,@Valid @ModelAttribute("unityFormatModel") ProductUnityFormatModel unityFormatModel,BindingResult result){
        if (result.hasErrors()) {
            Subject currentUser= SecurityUtils.getSubject();
            if(currentUser.isAuthenticated()) {
                if (unityFormatModel != null) {
                    PProduct product = productService.getProductByPrimaryKey(unityFormatModel.getProductId());
                    if (product != null) {
                        model.addAttribute("product", product);

                        String img = product.getProductImages();
                        //将图片地址分割
                        String[] imgs = img.split("\\|");
                        model.addAttribute("imgs", imgs);

                        //获取分类父分类名,递归查询,然后倒序转换
                        List<String> categoryNames = categoryService.getParentCategoryName(product.getpCategoryCategoryId());
                        Collections.reverse(categoryNames);

                        model.addAttribute("categoryNames", categoryNames);
                        return "/product_manage/product_publish_product_edit";
                    }
                }
                return "redirect:/error";
            }
           return "redirect:/login";
        }

        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (unityFormatModel.getProductId()!=null) {
                String imgins = "";
                if (unityFormatModel.getProductImgs()!=null&&unityFormatModel.getProductImgs().length > 0) {
                    String[] imgTmp = unityFormatModel.getProductImgs();
                    for (int $i = 0; $i < imgTmp.length; $i++) {
                        if (imgTmp[$i].equals("") && imgTmp[$i] != null) continue;
                        imgins += (imgTmp[$i] + "|");
                    }
                    imgins = imgins.substring(0, imgins.lastIndexOf("|"));
                }

                PProduct pProduct = new PProduct();
                pProduct.setProductId(unityFormatModel.getProductId());
//            pProduct.setpCategoryCategoryId(unityFormatModel.getCategoryId());//产品分类Id
                pProduct.setWxShopCategoryId(unityFormatModel.getShopCategoryId());//店铺分类Id
                pProduct.setProductCode(unityFormatModel.getProductCode());
                pProduct.setProductName(unityFormatModel.getProductName());
                //图片如果没有上传就不修改
                if (unityFormatModel.getProductImgs()!=null&&unityFormatModel.getProductImgs().length > 0) {
                    pProduct.setProductMainImage(unityFormatModel.getProductImgs()[0]);//主图片
                    pProduct.setProductImages(imgins);//上传的所有图片的URL地址
                }
                pProduct.setAddrProvinceName(unityFormatModel.getAddrProvinceName());//发货省份名
                pProduct.setAddrProvinceCode(unityFormatModel.getAddrProvinceCode());//发货省份地址代码
                pProduct.setAddrCityName(unityFormatModel.getAddrCityName());//发货城市名
                pProduct.setAddrCityCode(unityFormatModel.getAddrCityCode());//发货城市代码
                pProduct.setInventoryNum(Integer.parseInt(unityFormatModel.getInventoryNum()));//库存数
                pProduct.setMarketPrice(new BigDecimal(unityFormatModel.getMarketPrice()));//市场价
                pProduct.setSalePrice(new BigDecimal(unityFormatModel.getSalePrice()));//零售价
                pProduct.setProductDescription(unityFormatModel.getProductDescription());//商品描述
                pProduct.setFreight(new BigDecimal(unityFormatModel.getFreight()));//运费
                pProduct.setModifyOn(new Date());//修改时间

                productService.updateProductByPrimaryKey(pProduct);
                return "redirect:/product/productList?status=1";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 多条件查询
     * @param conditions
     * @return
     */
    @RequestMapping(value = "/product/searchProductByConditions",method = RequestMethod.POST)
    public String searchProductByConditions(Model model,ProductConditionsSelectModel conditions,
                                            @RequestParam(value = "page",defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum = currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user = userService.getUserByPhone(userPhoneNum);
            if (user != null) {
                //获取商店信息
                WxShop shop = wxShopService.getShopInforByUserId(user.getUserId());

                if(shop!=null) {

                    PageList<PProduct> pageList = productService.getProductByConditions(shop.getShopId(), conditions, PAGE_SIZE, page);
                    model.addAttribute("productList", pageList.list);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数

                    return "/product_manage/product_list_all";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }
}
